package com.dstation.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.dstation.domain.OrderInfo;
import com.dstation.domain.SubscriptionPackageInfo;
import com.dstation.domain.UserInfo;
import com.dstation.pay.AlipayConfig;
import com.dstation.service.interf.ICoinService;
import com.dstation.service.interf.ISubscriptionPackageService;
import com.dstation.service.interf.IUserService;
import com.dstation.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping(value = "/aliPay")
public class AliPayController {

    @Autowired
    private ICoinService coinService;

    @Autowired
    private ISubscriptionPackageService subscriptionPackageService;

    @Autowired
    private IUserService userService;
    /**
     * 支付界面
     * @param request
     * @param response
     * @param session
     * @throws Exception
     */
    @RequestMapping("/payPage")
    public void payPage(HttpServletRequest request, HttpServletResponse response,
                        HttpSession session) throws Exception {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);


        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
        String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
        //订单名称，必填
        String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");
        //商品描述，可空
        String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");
        //购买订阅套餐的类型
        String subPackType = request.getParameter("subPackType");


        /**
         * 以下是为了解决编码问题而创建的变量
         */
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no_db = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
        String total_amount_db = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
        //订单名称，必填
        String subject_db = request.getParameter("WIDsubject");
        //商品描述，可空
        String body_db = request.getParameter("WIDbody");
        //购买订阅套餐的类型
        String subPackType_db = request.getParameter("subPackType");

        //插入到数据库中一条订阅套餐信息
        SubscriptionPackageInfo subscriptionPackageInfo = new SubscriptionPackageInfo();
        subscriptionPackageInfo.setSubPackDescription("名称: " + subject_db + "\n商品描述：" + body_db + "\n金额:" + total_amount_db);
        subscriptionPackageInfo.setSubPackPrice(new BigDecimal(total_amount_db));
        subscriptionPackageInfo.setSubPackType(Integer.parseInt(subPackType_db));
        subscriptionPackageInfo.setCreateDate(new Timestamp(System.currentTimeMillis()));
        coinService.addSubScriptionOfCoin(subscriptionPackageInfo);

        // 插入到数据库一条订单信息
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(((UserInfo)session.getAttribute("userInfo")).getUserId());
        orderInfo.setSubPackId(Math.toIntExact(subscriptionPackageInfo.getSubPackId()));
        orderInfo.setTotal(new BigDecimal(total_amount));
        orderInfo.setStatus(Constants.NOT_ALREADY_PAY_TYPE_ORDER);
        orderInfo.setOrderNum(out_trade_no);
        orderInfo.setCreateDate(new Timestamp(System.currentTimeMillis()));
        coinService.addOrderInfo(orderInfo);
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no_db +"\","
                + "\"total_amount\":\""+ total_amount_db +"\","
                + "\"subject\":\""+ subject_db +"\","
                + "\"body\":\""+ body_db +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
//        String result = alipayClient.pageExecute(alipayRequest).getBody();

//        PrintWriter out = response.getWriter();
        //输出
//        out.print(result);

        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=" + AlipayConfig.charset);
        response.getWriter().write(form);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }


    @RequestMapping("/notifyUrl")
    public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        PrintWriter out = response.getWriter();
        //——请在这里编写您的程序（以下代码仅作参考）——
        /* 实际验证过程建议商户务必添加以下校验：
        1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        if(signVerified) {//验证成功

            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            //商户订单号
            String out_trade_no_db = request.getParameter("out_trade_no");

            //支付宝交易号
            String trade_no_db = request.getParameter("trade_no");

            //交易状态
            String trade_status_db = request.getParameter("trade_status");

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){    //支付完成后修改数据库信息
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
            }

            out.println("success");

        }else {//验证失败
            out.println("fail");

            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }

        //——请在这里编写您的程序（以上代码仅作参考）——
    }

    /**
     * 付款成功后会回调该函数
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/returnUrl")
    public String returnUrl(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws Exception {

        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        PrintWriter out = response.getWriter();
        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = request.getParameter("out_trade_no");

            //支付宝交易号
            String trade_no = request.getParameter("trade_no");

            //付款金额
            String total_amount = request.getParameter("total_amount");

            //商户订单号
            String out_trade_no_db = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no_db = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount_db = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);

            OrderInfo order = coinService.findOrderByOrderNum(out_trade_no_db);
            UserInfo userInfo = (UserInfo)session.getAttribute("userInfo");
            if (order != null){
                // 1. 修改订单状态为已支付状态
                 coinService.alterOrderStatusByOrderNo(out_trade_no_db, Constants.ALREADY_PAY_TYPE_ORDER);
                SubscriptionPackageInfo subscriptionPackageInfo = subscriptionPackageService.findSubscriptionPackageBySubPackId(order.getSubPackId());
                if (subscriptionPackageInfo.getSubPackType() == 0){
                    // 2. 为用户增加硬币数量
                    System.out.println("subscriptionPackageInfo = " + subscriptionPackageInfo);
                    double coinNum = Double.valueOf(subscriptionPackageInfo.getSubPackPrice().doubleValue() * Constants.CASH_TRANSFER_COIN) + userInfo.getUserBalance();
                    userInfo.setUserBalance(coinNum);
                }else{
                    int privilegetimes = Integer.valueOf(subscriptionPackageInfo.getSubPackDescription()) + userInfo.getPrivilegetimes();
                    userInfo.setPrivilegetimes(privilegetimes);
                }
                // 3. 更新当前session用户信息
                userService.alterUserInfo(userInfo);
//                UserInfo userInfo = userService.findUserInfoByUserId(((UserInfo) session.getAttribute("userInfo")).getUserId());
                session.removeAttribute("userInfo");
                session.setAttribute("userInfo", userInfo);
            }

        }else {
            out.println("验签失败");
        }
        return "redirect:/user/userHomePage";   //重定向到主界面
    }
}
